<template>
  <div class="map">
    <div id="container"></div>
    <div class="input-card" style="width: 120px">
      <!-- 编辑区域 -->
      <div class="edit_box">
        <div class="edit_btn">
          <div class="add" @click="toAdd">新增路线</div>
        </div>
      </div>
      <div class="content" v-show="isEdit">
        <!-- 路线名称 -->
        <div class="lie">
          <div class="name">路线名称：</div>
          <input
            type="text"
            class="route_input"
            v-model="addName"
            placeholder="请输入路线名称"
          />
        </div>
        <div class="color_edit">
          <div class="lie">
            <div class="left">
              <div class="name">颜色：</div>
              <el-color-picker
                class="color_input"
                v-model="addColor"
                @change="EditColor($event)"
              />
            </div>
          </div>
          <div class="lie">
            <div class="name">粗细：</div>
            <el-input-number
              v-model="addStrok"
              class="thickness_input"
              @change="addChange"
              :min="1"
              :max="15"
            />
          </div>
        </div>
        <div class="btn">
          <div class="edit save" @click="toAddSave">保存</div>
          <div class="edit del" @click="delAdd">删除</div>
        </div>
      </div>
      <hr />
      <!-- 路线数据 -->
      <ul class="ul_path">
        <li class="li_path" v-for="(item, index) in pathData" :key="item.id">
          <div class="content">
            <!-- 路线名称 -->
            <div class="lie">
              <div class="name">路线名称：</div>
              <input
                type="text"
                class="route_input"
                v-model="item.name"
                placeholder="请输入路线名称"
              />
            </div>
            <div class="color_edit">
              <div class="lie">
                <div class="left">
                  <div class="name">颜色：</div>
                  <el-color-picker class="color_input" v-model="item.cloor" />
                </div>
              </div>
              <div class="lie">
                <div class="name">粗细：</div>
                <el-input-number
                  v-model="item.strok"
                  class="thickness_input"
                  @change="editChange"
                  :min="1"
                  :max="15"
                />
              </div>
            </div>
          </div>
          <div class="btn">
            <div class="edit" v-if="item.isShow" @click="toEdit(item.id, index)">
              修改
            </div>
            <div class="edit save" v-else @click="toEditSave(item.id)">保存</div>
            <div class="edit del" @click="toEditDel(item.id, item.name)">删除</div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
var map = {};
export default {
  data() {
    return {
      bezierCurveEditor: {},
      bezierCurveData: [],
      map: null,
      isEdit: false, //新增路线
      addName: "路线" + Math.round(Math.random() * 1000), //路线名称
      addStrok: 5,
      addColor: "#409eff",
      addPath: [],
      pathData: JSON.parse(localStorage.getItem("mapPathData")) || [
        {
          id: 1,
          name: "水厂01",
          cloor: "#409eff",
          strok: 6,
          isShow: true,
          path: [
            //每个弧线段有两种描述方式
            [116.37, 39.91], //起点
            //第一段弧线
            [116.380298, 39.907771, 116.38, 39.9], //控制点，途经点
            //第二段弧线
            [116.385298, 39.907771, 116.4, 39.9], //控制点，途经点//弧线段有两种描述方式1
            //第三段弧线
            [
              //弧线段有两种描述方式2
              [116.392872, 39.887391], //控制点
              [116.40772, 39.909252], //控制点
              [116.41, 39.89], //途经点
            ],
            //第四段弧线
            [116.423857, 39.889498, 116.422312, 39.899639, 116.425273, 39.902273],
            //控制点，控制点，途经点，每段最多两个控制点
          ],
        },
        {
          id: 2,
          name: "水厂12",
          cloor: "#09f000",
          strok: 5,
          isShow: true,
          path: [
            [116.453322, 39.920255],
            [116.460703, 39.897555],
            [116.452292, 39.892353],
            [116.439846, 39.891365],
          ],
        },
        {
          id: 3,
          name: "水厂09",
          cloor: "#d93025",
          strok: 5,
          isShow: true,
          path: [
            [116.388469, 39.922285],
            [116.389504, 39.919513],
            [116.398653, 39.923851],
            [116.404356, 39.913531],
            [116.417564, 39.911845],
          ],
        },
      ],
      maskData: [
        {
          id: 1,
          img: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png",
          title: "源水井位置",
          position: {
            x: "90.068996",
            y: "47.077216",
          },
          imageOffset: {
            x: -9,
            y: -3,
          },
        },
        {
          id: 2,
          img: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png",
          title: "第一个末端压力采集点",
          position: {
            x: "90.140329",
            y: "46.306952",
          },
          imageOffset: {
            x: -9,
            y: -3,
          },
        },
        {
          id: 2,
          img: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png",
          title: "第二个末端压力采集点",
          position: {
            x: "90.21964",
            y: "46.520015",
          },
          imageOffset: {
            x: -9,
            y: -3,
          },
        },
      ],
    };
  },
  mounted() {
    this.createMap();
  },
  methods: {
    // 新增路线-----------------------------------------------------------------------
    // 路线粗细
    addChange(value) {
      // console.log("路线粗细-===",value);
      this.addStrok = value;
    },
    // 清空表单数据
    formData() {
      this.addName = "路线" + Math.round(Math.random() * 1000);
      this.addColor = "#409eff";
      this.addStrok = 5;
      this.addPath = [];
      this.bezierCurveData = [];
    },
    // 取消新增路线
    delAdd() {
      this.$confirm("此操作将永久删除该新增路线, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 清空表单数据
          this.formData();
          this.isEdit = false;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 面板颜色改变
    EditColor(e) {
      // console.log("e===",e);
      this.addColor = e;
    },
    // 新增路线
    toAdd() {
      this.isEdit = true;
      this.$message({
        message: "开启，新增路线。",
        type: "success",
      });

      this.bezierCurveEditor = new AMap.BezierCurveEditor(map);
      // 开始编辑新增路线
      this.bezierCurveEditor.on("addnode", function (event) {
        // 增加一个节点时触发此事件
        // console.log("addnode", event);
      });
      this.bezierCurveEditor.on("adjust", function (event) {
        // 调整折线上某个点时触发此事件
        // console.log("adjust", event);
      });
      this.bezierCurveEditor.on("removenode", function (event) {
        // 删除一个节点时触发此事件
        // console.log("removenode", event);
      });
      this.bezierCurveEditor.on("end", (event) => {
        // 调用close之后触发该事件，target即为编辑后的覆盖物对象
        // console.log("end", event);
        // 保存编辑的路线
        this.addPath = event.target.$x[0];
        // 判断不保存只有两个坐标的数据
        if (this.addPath.length == 2) {
          this.addPath = [];
          return;
        }
        // 新增数据
        let data = {
          id: Math.round(Math.random() * 100),
          name: this.addName,
          cloor: this.addColor,
          strok: this.addStrok,
          isShow: true,
          path: this.addPath,
        };
        this.pathData.unshift(data);
        // 缓存本地
        localStorage.setItem("mapPathData", JSON.stringify(this.pathData));
        // 重新绘制路线
        this.createMap();
        this.isEdit = false;
        // 清空表单数据
        this.formData();
        this.$message({
          message: "保存，新增路线。",
          type: "success",
        });
      });

      // 打开编辑路线
      this.bezierCurveEditor.open();
    },
    // 保存新增路线
    toAddSave() {
      this.$confirm("此操作将保存新增路线, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 关闭新增路线编辑
          this.bezierCurveEditor.close();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消继续编辑",
          });
        });
    },

    // 修改已有的路线------------------------------------------------------------------

    // 修改路线粗细
    editChange(value) {
      // console.log("修改路线粗细",value);
    },

    //  删除已有路线
    toEditDel(id, name) {
      this.$confirm("此操作将永久删除该路线, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = this.pathData.filter((item) => item.id !== id);
          this.pathData = data;
          this.bezierCurveData = [];
          // 重新绘制路线
          this.createMap();
          this.$message({
            message: `成功删除，${name} 路线!!!`,
            type: "success",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 修改已有路线
    toEdit(id, index_id) {
      this.$confirm("此操作将打开编辑修改该路线, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            message: "已打开编辑模式",
            type: "success",
          });
          this.pathData.map((val) => {
            if (val.id === id) {
              val.isShow = false;
              this.bezierCurveData.forEach((item, index) => {
                if (index === index_id) {
                  //选择修改的路线
                  this.bezierCurveEditor = new AMap.BezierCurveEditor(map, item);
                  this.bezierCurveEditor.on("addnode", function (event) {
                    // 增加一个节点时触发此事件
                    // console.log("addnode", event);
                  });
                  this.bezierCurveEditor.on("adjust", function (event) {
                    // 调整折线上某个点时触发此事件
                    // console.log("adjust", event);
                  });
                  this.bezierCurveEditor.on("removenode", function (event) {
                    // 删除一个节点时触发此事件
                    // console.log("removenode", event);
                  });

                  this.bezierCurveEditor.on("end", (event) => {
                    // 调用close之后触发该事件，target即为编辑后的覆盖物对象
                    // console.log("end", event);
                    // 保存编辑的路线
                    val.path = event.target.$x[0];
                    // 判断不保存只有两个坐标的数据
                    if (val.path.length == 2) {
                      this.addPath = [];
                      return;
                    }
                    // 缓存本地
                    localStorage.setItem("mapPathData", JSON.stringify(this.pathData));
                    val.isShow = true;
                    this.$message({
                      message: `修改 ${val.name} 路线，成功。`,
                      type: "success",
                    });
                    // 重新绘制路线
                    this.createMap();
                  });

                  // 打开编辑路线
                  this.bezierCurveEditor.open();
                }
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
    },
    // 保存修改已有路线
    toEditSave(id) {
      this.pathData.map((val) => {
        if (val.id == id) {
          if (val.path.length == 2) {
            this.$message({
              type: "info",
              message: "无路线数据保存",
            });
            return;
          }
          // 关闭已有路线编辑
          this.bezierCurveEditor.close();
        }
      });
    },
    // 创建地图
    createMap() {
      // 引入高德地图
      AMapLoader.load({
        key: "e24445773dbfa2a86945b7fac01ab6a5",
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺少时默认为 1.4.15
        plugins: [
          "AMap.Scale",
          "AMap.GeoJSON",
          "AMap.BezierCurve",
          "AMap.BezierCurveEditor",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等，更多插件请看官方文档
      }).then((AMap) => {
        //填入地图容器div的id
        map = new AMap.Map("container", {
          zoom: 10, //设置地图的缩放级别
          // zooms: [8, 20], //设置地图的缩放级别区间
          // center: [116.400274, 39.905812], //设置地图中心点坐标
          center: [90.38, 46.67], //设置地图中心点坐标
          mapStyle: "amap://styles/blue", //设置地图的显示样式，更改darkblue为你想要的样式
          features: ["bg", "building", "road", "point"], //设置地图的底图元素，缺少则显示全部元素，bg区域面、point兴趣点、road道路及道路标注、building建筑物
        });
        map.getCenter();

        var MarkerList = [];
        // 绘制标记点
        this.maskData.forEach((val) => {
          console.log("val.position", `${val.position.x},${val.position.y}`);
          // 标注的图标
          var Icon = new AMap.Icon({
            // 图标尺寸
            size: new AMap.Size(25, 34),
            // 图标的取图地址
            image: val.img,
            // 图标所用图片大小
            imageSize: new AMap.Size(135, 40),
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(val.imageOffset.x, val.imageOffset.y),
          });

          // 标记点信息
          var Marker = new AMap.Marker({
            position: new AMap.LngLat(val.position.x, val.position.y),
            icon: Icon,
            offset: new AMap.Pixel(-13, -30),
          });
          // 标记点提示信息
          Marker.setLabel({
            direction: "top",
            offset: new AMap.Pixel(10, 0), //设置文本标注偏移量
            content: `<div class='info'>${val.title}</div>`, //设置文本标注内容
          });
          MarkerList.push(Marker);
        });

        map.add(MarkerList);
        // 适应中心点
        // map.getCenter();
        map.setFitView(null, false, [150, 60, 100, 60]);
        map.getCenter();
        //
        //绘制路线
        this.pathData.forEach((val) => {
          let bezierCurve = new AMap.BezierCurve({
            path: val.path,
            borderWeight: 0,
            strokeColor: val.cloor,
            strokeOpacity: 1,
            strokeWeight: val.strok,
            showDir: true,
            // 线样式还支持 'dashed'
            strokeStyle: "dashed",
            // strokeStyle是dashed时有效
            strokeDasharray: [10, 10],
            lineJoin: "round",
            lineCap: "round",
            zIndex: 50,
          });
          this.bezierCurveData.push(bezierCurve);
          map.add(bezierCurve);
        });

        // 缩放地图到合适的视野级别
        // map.setFitView(this.bezierCurveData);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
ul li {
  list-style: none;
}
.map {
  width: 100vw;
  height: 100vh;
  #container {
    width: 100%;
    height: 100%;
  }
  .input-card {
    width: 300px !important;
    position: absolute;
    top: 40px;
    right: 20px;
    background-color: #fff;
    padding: 20px;
    border: 1px solid #409eff;
    box-sizing: border-box;
    font-size: 14px;
    .edit_box {
      .edit_btn {
        display: flex;
        margin-bottom: 30px;
        margin-left: 0;
        .add {
          width: 120px;
          height: 30px;
          text-align: center;
          color: #fff;
          font-size: 16px;
          background-color: #409eff;
          border-radius: 6px;
          line-height: 30px;
        }
        .save {
          margin-left: 20px;
        }
      }
    }
    .content {
      .name {
        font-weight: 600;
      }
      .color_edit {
        display: flex;
      }
      .lie {
        height: 30px;
        line-height: 30px;
        display: flex;
        margin-bottom: 15px;

        .route_input {
          margin-top: 2px;
          height: 26px;
          width: 130px;
          outline: none;
          padding-left: 8px;
          font-size: 13px;
          border: 1px solid #409eff;
        }
        .color_input {
          margin-top: 5px;
          margin-right: 20px;
          ::v-deep .el-color-picker__trigger {
            width: 20px;
            height: 20px;
            padding: 0;
            border: none;
            border-radius: none;
          }
          ::v-deep .el-color-picker__icon {
            font-size: 0;
          }
          ::v-deep .el-color-picker__color {
            border: none;
          }
          ::v-deep .el-color-picker__color-inner {
            border-radius: 4px;
          }
        }
        .left,
        .right {
          display: flex;
        }
        .thickness_input {
          width: 80px;
          ::v-deep .el-input__inner {
            height: 30px;
          }
          ::v-deep .el-input-number__decrease,
          ::v-deep .el-input-number__increase {
            width: 25px;
          }
        }
        ::v-deep .el-input-number {
          line-height: 28.5px !important;
        }
        ::v-deep .el-input-number .el-input__inner {
          padding-left: 0;
          padding-right: 0;
        }
      }
    }
  }
  .ul_path {
    height: 38vh;
    overflow-y: scroll;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .li_path {
    // background-color: pink;
    margin-top: 20px;
    border-bottom: 1px dashed #409eff;
    .btn {
      display: flex;
      .edit {
        width: 60px;
        height: 25px;
        text-align: center;
        color: #fff;
        background-color: #67c23a;
        border-radius: 6px;
        line-height: 25px;
        margin-bottom: 10px;
        margin-right: 10px;
      }
      .del {
        background-color: #f56c6c;
      }
      .save {
        background-color: #409eff;
      }
    }
  }
  .btn {
    display: flex;
    .edit {
      width: 60px;
      height: 25px;
      text-align: center;
      color: #fff;
      background-color: #67c23a;
      border-radius: 6px;
      line-height: 25px;
      margin-bottom: 10px;
      margin-right: 10px;
    }
    .del {
      background-color: #f56c6c;
    }
    .save {
      background-color: #409eff;
    }
  }
}
</style>
